<template>
  <div class="table-all">
  <!-- 搜索区 -->
  <div class="app-container search-box">
    <SearchForm
      :form="searchData.form"
      :options="searchData.options"
      @searchUpdate="search"
      @resetSearchData="resetSearchData"
      @toLoadMethods="toLoadMethods"
    ></SearchForm>
  </div>
  <!-- 按钮区 -->
  <div class="app-container table-box">
    <div class="table-main">
      <!-- 表格 -->
      <v-table
        title="巡查模板信息"
        v-if="tableMainHeight>0"
        :table-columns="tableColumns"
        :table-data="tableData"
        :loading="loading"
        :is-index="false"
        @update:selectionChange="onSelectChange"
        ref="table"
        :maxHeight="tableMainHeight">
        <template #topButtonList>
          <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
        </template>
        <template #belong="scope">
          {{getBelong(scope.row.patrolModelBelongList)}}
        </template>
        <template #modelType="scope">
          {{getDictValue(scope.row.modelType, modelTypeOptions)}}
        </template>
        <template #busiLargeType="scope">
          {{getDictValue1(scope.row.busiLargeType, bClassifyOptions)}}
        </template>
        <template #busiSmallType="scope">
          {{getDictValue1(scope.row.busiSmallType, sClassifyOptions)}}
        </template>
        <template #disableFlag="scope">
          {{getDictValue(scope.row.disableFlag, disableFlagOptions)}}
        </template>
        <template #operation="scope">
          <a v-hasPermission="['patrolModel:detail']" class="table-btn-view table-operation"
             @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
          <a v-if="scope.row.updateAble"
             v-hasPermission="['patrolModel:update']" class="table-btn-edit table-operation"
             @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>
          <a v-if="scope.row.updateAble && scope.row.disableFlag == 0"
             v-hasPermission="['patrolModel:add']" class=" table-btn-delete table-operation"
             @click="updateDisAbled(scope.row, 1)">{{$t('table.disable')}}</a>
          <a v-if="scope.row.updateAble && scope.row.disableFlag == 1"
             v-hasPermission="['patrolModel:add']" class="table-btn-edit table-operation"
             @click="updateDisAbled(scope.row, 0)">{{$t('table.able')}}</a>
          <a v-if="scope.row.updateAble"
             v-hasPermission="['patrolModel:delete']" class="table-btn-delete table-operation"
             @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
        </template>
      </v-table>
    </div>
    <div class="table-page">
      <!-- 页码 -->
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="search"/>
    </div>
  </div>
  <!-- 详情 -->
  <detailDialog :dialog-visible="detailDialogShow"
                @success="editSuccess"
                @close="editClose"
                :bClassifyOptions = "bClassifyOptions"
                :modelTypeOptions = "modelTypeOptions"
                :openType="detailOpenType"
                :id="detailId"
                :title="detailTitle"
  ></detailDialog>
  </div>
</template>

<script>
  import { patrolModelPage,patrolModelDelete,patrolModelUpdateDisable } from '@/api/risk/patrol'
  import { treeDataChild} from '@/api/risk/treeData'
  import SearchForm from '@/components/searchForm/index'
  import ButtonForm from '@/components/ButtonForm/index'
  import VTable from '@/components/VTable/index'
  import Pagination from '@/components/Pagination/index'
  import detailDialog from './detail.vue'
  export default {
    components:{
      VTable,Pagination,detailDialog,SearchForm,ButtonForm
    },
    data(){
      return{
        tableColumns:[

          {
            prop: 'projectName',
            label: '所属工地',
            minWidth: '150',
            slotname: 'projectName',
            options: {}
          },

          {
            prop: 'modelName',
            label: '表单名称',
            minWidth: '150',
            slotname: 'modelName',
            options: {}
          },
          {
            prop: 'modelType',
            label: '表单类型',
            minWidth: '150',
            slotname: 'modelType',
            options: {}
          },
          {
            prop: 'belong',
            label: '所属单位',
            minWidth: '150',
            slotname: 'belong',
            options: {}
          },
          {
            prop: 'busiLargeType',
            label: '业务专题大类',
            minWidth: '150',
            slotname: 'busiLargeType',
            options: {}
          },
          {
            prop: 'busiSmallType',
            label: '业务专题细类',
            minWidth: '150',
            slotname: 'busiSmallType',
            options: {}
          },
          {
            prop: 'disableFlag',
            label: '状态',
            minWidth: '100',
            slotname: 'disableFlag',
            options: {}
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: '150',
            slotname: 'createBy',
            options: {}
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: '150',
            slotname: 'createTime',
            options: {}
          },
          {
            prop: 'operation',
            label: '操作',
            width: '200',
            align: 'center',
            slotname: 'operation',
            overflow: false,
            fixed: 'right'
          }
        ],
        tableData:[],
        selection: [],
        loading:false,
        total:1,
        pageNum:1,
        pageSize:10,
        detailOpenType:"add",
        detailDialogShow:false,
        detailId:"",
        detailTitle:"新增",
        dict:{},
        searchData:{
          form:{
            modelName:'',
            busiLargeType:'',
            busiSmallType:'',
            belongUnitName:""
          },
          options:[
            {
              title:'表单名称',
              key: "modelName",
              type: "text",
            },
            {
              title:'业务专题大类',
              key: "busiLargeType",
              type: "select",
              multiple:false,
              event: 'changeLargeType',
              option: {
              data: this.bClassifyOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "name", // 指定value对应data的字段
              },
              },
            },
            {
              title:'业务专题细类',
              key: "busiSmallType",
              type: "select",
              multiple:false,
              option: {
                data: this.sClassifyOptionsForm,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "code", // 指定value对应data的字段
                },
              },
            },
            // {
            //   title:'所属单位',
            //   key: "belongUnitName",
            //   type: "text",
            // },
          ]
        },
        buttonList:[
          {name:'新增',methods:'handleAdd',type:'primary',  hasPremission:["patrolModel:add"]},
          //{name:'类似新增',methods:'handleLikeAdd',  hasPremission:["patrolModel:add"]},
        ],
        tableMainHeight: 0,
        // 字典
        bClassifyOptions:[],
        sClassifyOptions:[],
        sClassifyOptionsForm:[],
        modelTypeOptions:[],
        disableFlagOptions:[]
      }
    },
    watch: {
      // 字典
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='busiLargeType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptionsForm':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='busiSmallType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    methods:{
      getBelong(list){
        if(list!=null && list.length!=0){
           return list.map(t=> t.belongUnit).join(",")
        }
        return ''
      },
      onSelectChange(selection) {
        this.selection = selection
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      changeLargeType(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.searchData.form.busiLargeType
        treeDataChild(queryData).then(res=>{
          if(res.code==200) {
           this.sClassifyOptionsForm = res.data
          }
        })
        this.searchData.form.busiSmallType = ''
      },
      handleDetail(row){
        this.detailId = row.id
        this.detailOpenType = "detail"
        this.detailTitle="详情"
        this.detailDialogShow = true
      },
      handleUploadSuccess(){
        this.search()
        this.importDialog.isVisible = false
      },
      getCheckBoxValue(value,option){
        if(!value){
          return
        }
        let temp = []
        let data = value.split(",")
        data.forEach(t=>{
          let item = option.find(x=> x.value == t)
          if(item != undefined){
            temp.push(item.label)
          }
        })
        return temp.join(",")
      },
      getDictValue(value,option){
        let item = option.find(t=> t.value == value)
        if(item!=undefined){
          return item.label
        }
        return value
      },
      getDictValue1(value,option){
        let item = option.find(t=> t.name == value)
        if(item!=undefined){
          return item.label
        }
        return value
      },
      editClose(){
        this.detailDialogShow = false
      },
      editSuccess(){
        this.search()
        this.detailDialogShow = false
      },
      search(){
        this.fetch({
          ...this.searchData.form,
        })
      },
      fetch(params={}){
        params.pageSize = this.pageSize
        params.pageNum = this.pageNum
        this.loading = true
        patrolModelPage(params).then(async res=>{
          if(res.code==200){
            this.total = res.data.total
            this.tableData = res.data.rows
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      // 重置搜索条件
      resetSearchData(){
        this.searchData.form = {
          modelName:'',
          busiLargeType:'',
          busiSmallType:'',
          belongUnitName:""
        }
        this.sClassifyOptionsForm = []
      },
      // 触发按钮区域按钮方法
      clickButton(methods){
        this[methods]()
      },
      handleAdd(){
        this.detailOpenType = "add"
        this.detailTitle = "新增"
        this.detailDialogShow = true
      },
      handleLikeAdd(){
        if(this.selection.length!=1){
          this.$message.warning("请选择一个模板类似新增")
          return
        }
        console.log("this.selection====》",this.selection)
        this.detailId = this.selection[0].id
        this.detailOpenType = "likeAdd"
        this.detailTitle = "新增"
        this.detailDialogShow = true
      },
      handleEdit(row){
        this.detailId = row.id
        this.detailOpenType = "edit"
        this.detailTitle="编辑"
        this.detailDialogShow = true
      },

      closeDialog(){
        this.detailDialogShow = false
      },
      updateDisAbled(row, value){
        let tips = value == 1 ? "选中数据将被禁用, 是否继续？" : "选中数据将开启使用, 是否继续？";
        this.$confirm(tips, this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          patrolModelUpdateDisable(row.id,value).then(res=>{
            if(res.code==200){
              this.$message({
                message: "更改成功！",
                type: 'success'
              })
              this.search()
            }else{
              this.$message({
                message: "更改成功！",
                type: 'error'
              })
            }
          }).finally(final=>{
            this.loading = false
          })
        })
      },
      singleDelete(row){
        this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          patrolModelDelete(row.id).then(res=>{
            if(res.code==200){
              this.$message({
                message: this.$t('tips.deleteSuccess'),
                type: 'success'
              })
              this.search()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          }).finally(final=>{
            this.loading = false
          })
        })
      }
    },
    activated(){
      this.fetch()
    },
    created(){
      // 获取字典值
      this.bClassifyOptions = []
      this.$commonJs.filterDataDict("hazardBClassify",this.bClassifyOptions)
      this.sClassifyOptions = []
      this.$commonJs.filterDataDict("hazardSClassify",this.sClassifyOptions)
      this.modelTypeOptions = []
      this.$commonJs.filterDataDict("patrolModelType",this.modelTypeOptions)
      this.disableFlagOptions =[]
      this.$commonJs.filterDataDict("patrolDisableFlag",this.disableFlagOptions)
    },
    mounted(){
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }
  }
</script>

<style lang="scss" scoped>
  .table-all {
    display: flex;
    flex-direction: column;
    height: 100%;

  .search-box {
    padding-bottom: 6px;
  }

  .table-box {
    padding-top: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;

  .table-main {
    flex: 1;
    overflow: auto;
  }

  .table-page {
  // padding-top: 10 px;
  // padding-bottom: 10 px;
  }

  ::v-deep .pagination-container {
    text-align: right;
  }

  }
  }
</style>
